package com.zegome.game.me;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.util.Log;

import com.zegome.game.main.ZegomeActivity;

/**
 * (C) 2013 ZeroTeam
 * @author QuanLT
 */

public final class AndroidHelper {

	// ===========================================================
	// Constants
	// ===========================================================

	// ===========================================================
	// Fields
	// ===========================================================

	// ===========================================================
	// Constructor
	// ===========================================================

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	// ===========================================================
	// Methods
	// ===========================================================
	public static int getVersionCode(final Activity activity){
		try {
			return activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e) {
			return -1;
		}
	}
	
	public static void openGooglePlay(final Activity activity, String appPackageName){		
		try {
		    activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
		} catch (android.content.ActivityNotFoundException anfe) {
		    activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName)));
		}
	}
	
	public static void openlink(final ZegomeActivity activity, final String link){
		activity.postHandler(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Intent i = new Intent(Intent.ACTION_VIEW, 
					       Uri.parse(link));
					activity.startActivity(i);
			}
		});
	}
	
	public static String getEmail(final Activity activity) {
		final AccountManager accountManager = AccountManager.get(activity.getBaseContext());
		final Account account = getAccount(accountManager);
		if (account == null) {
			return "";
		} else {
			return account.name;
		}
	}

	public static Account getAccount(AccountManager accountManager) {
		final Account[] accounts = accountManager.getAccountsByType("com.google");
		final Account account;
		if (accounts.length > 0) {
			account = accounts[0];
		} else {
			account = null;
		}
		return account;
	}

	public static boolean isNetworkAvailable(final Activity activity) {
		final ConnectivityManager connectivityManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
		final NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
		return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}

	public static String convertStreamToString(final InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	
	public final String els_url = "http://zegome.com/service/index/";
	// "http://192.168.0.111/zegome-service/Resources/version-1/index/";
	public final String els_url_resource = "http://zegome.com/service/";
	// "http://192.168.0.111/zegome-service/Resources/version-1/";
	public String sessionId;
//	public DefaultHttpClient httpclient;
	
	public void sendCheckVersion(final ZegomeActivity activity, final DefaultHttpClient httpClient, final String url, final List<NameValuePair> nameValuePairs, final INetworkActionListener listener)
	{		
		final AsyncTaskNetWork net = new AsyncTaskNetWork(httpClient,
				new INetWorkAction() {
					
					@Override
					public String send() {
						// TODO Auto-generated method stub
						String responseText = null;
						final HttpPost httpost = new HttpPost(url);

					     try{
					    	 httpost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
					     }
					     catch(Exception ex){}
						HttpResponse response = null;
						try {
							response = httpClient.execute(httpost);
						} catch (Exception e) {
							// e.printStackTrace();
						}
						if (response == null) {
							// ctr.stageHelper.createDialog(stage, tweenManager,
							// "Lối kết nối!", 1, null, null);
							return null;
						}

						int status_code = response.getStatusLine().getStatusCode();
						// log("" + status_code);
						HttpEntity entity = response.getEntity();
						if (entity != null || status_code == 200 || status_code == 201) {
							InputStream instream = null;
							try {
								instream = entity.getContent();
							} catch (IllegalStateException e) {
								e.printStackTrace();
							} catch (IOException e) {
								e.printStackTrace();
							}

							responseText = convertStreamToString(instream);

							// Closing the input stream will trigger connection
							// release
							try {
								instream.close();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
						listener.onSendProcessor(responseText);
						log("Response Check Version: " + responseText);
						return responseText;
					}
					
					@Override
					public void receive(String responseText) {
						listener.onReceiverProcessor(responseText);
					}
				});
		activity.postHandler(new Runnable() {
			
			@Override
			public void run() {
				net.send();
			}
		});
	}
	
	public static void sendMail(final ZegomeActivity activity, final DefaultHttpClient httpClient, final String url, final List<NameValuePair> nameValuePairs, final INetworkActionListener listener) {		
		final AsyncTaskNetWork net = new AsyncTaskNetWork(httpClient,
				new INetWorkAction() {
					
					@Override
					public String send() {
						String responseText = null;
						final HttpPost httpost = new HttpPost(url);

					     
					     try{
					    	 httpost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
					     }
					     catch(Exception ex){}
						HttpResponse response = null;
						try {
							response = httpClient.execute(httpost);
						} catch (Exception e) {
							 e.printStackTrace();
						}
						if (response == null) {
							return null;
						}

						int status_code = response.getStatusLine()
								.getStatusCode();
						HttpEntity entity = response.getEntity();
						if (entity != null || status_code == 200 || status_code == 201) {
							InputStream instream = null;
							try {
								instream = entity.getContent();
							} catch (IllegalStateException e) {
								e.printStackTrace();
							} catch (IOException e) {
								e.printStackTrace();
							}

							responseText = convertStreamToString(instream);

							try {
								instream.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
						listener.onSendProcessor(responseText);
						log("Response Save mail: " + responseText);
						return responseText;
					}
					
					@Override
					public void receive(String responseText) {
						listener.onReceiverProcessor(responseText);
					}
				});
		activity.postHandler(new Runnable() {
			
			@Override
			public void run() {
				net.send();
			}
		});
	}
	
	public static void log(String string) {
		// TODO Auto-generated method stub
		if(string==null)
			return;
		Log.e("serverthienkien",string);
	}
	
	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================
}
